// 富文本调整内部标签宽度
import {
	homeApi
} from "@/api/index"
export function formatRichText(html) {
	html = html + ''
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
			'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block"');
	return newContent;
}
// 上次文件
export function uploadFilePromise(url) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: 'https://www.cnpowder.com.cn/user/miniprogramwx/txl.php?do=uploadImageFile',
			filePath: url,
			name: 'upimgfile',
			success: (res) => {
				resolve(JSON.parse(res.data))
			}
		})
	})
}
// 登录校验
export function isLogin(type = 1) {
	if (type == '1') {
		if (!uni.getStorageSync('token')) {
			uni.showModal({
				content: '登录失效请登录',
				success: (e) => {
					if (e.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
		}
	} else {
		if (!uni.getStorageSync('token')) {
			uni.showModal({
				title: "提示",
				content: "登录失效请登录",
				showCancel: false,
				success(res) {
					setTimeout(() => {
						uni.navigateTo({
							url: "/pages/login/login",
						})
					}, 1000);
				},
			});
		}
	}
}
// 正则校验
export function isPhone(phone) { //手机号
	const reg = /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/;
	return reg.test(phone);
}
export function isEmail(email) { //邮箱
	var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
	return reg.test(email);
}

// 跳转方法
export function link(url, isTo = false) {
	let top = url.substring(0, 4);
	if (top == 'http') {
		uni.getSystemInfo({
			success: function(info) {
				if (info.uniPlatform == 'web') {
					window.location.href = url
				} else {
					goUrl(`/news/publicHtml/index?url=${encodeURIComponent(url)}`)
				}
			}
		})
	} else {
		if (isTo) {
			uni.redirectTo({
				url: url
			})
		} else {
			goUrl(url)
		}
	}
}
export function goUrl(url, type = 0) {
	if (type == 0) { //默认页面跳转 传入1跳 tabbar
		uni.navigateTo({
			url: url
		})
	} else {
		uni.switchTab({
			url: url
		})
	}
}
// 文件下载
export async function upFile(fileid, t = 'info') {
	let data = {
		do: 'downfile',
		id: fileid,
		t: t
	}
	let res = await homeApi.publicGet(data)

	if (res.error_no == '0') {
		if (uni.getSystemInfoSync().uniPlatform == 'web') {
			window.open(res.columns[0].fileurl);
		} else {
			uni.showLoading({
				title: '下载中...'
			});
			uni.downloadFile({
				url: res.columns[0].fileurl,
				header: {
					'Authorization': uni.getStorageSync("token") // 自定义请求
				},
				success: (e) => {
					uni.openDocument({
						filePath: e.tempFilePath,
						showMenu: true,
						success() {
							uni.hideLoading();
						},
						fail() {
							uni.hideLoading();
						}
					})
				},
				fail: (e) => {
					uni.hideLoading();
				}
			})
		}
	} else {
		uni.showToast({
			title: res.error_msg,
			icon: 'none',
			duration: 2000
		});
	}
}
// 文件下载
export async function upFiles(fileUrl) {
	uni.showLoading({
		title: '下载中...'
	});
	uni.downloadFile({
		url: fileUrl,
		header: {
			'Authorization': uni.getStorageSync("token") // 自定义请求
		},
		success: (e) => {
			uni.openDocument({
				filePath: e.tempFilePath,
				showMenu: true,
				success() {
					uni.hideLoading();
				},
				fail() {
					uni.hideLoading();
				}
			})
		},
		fail: (e) => {
			uni.hideLoading();
		}
	})
}
// 时间格式
export async function setTime(time) {
	if (time) {
		let date = new Date(time)
		let year = date.getFullYear();
		let month = ('0' + (date.getMonth() + 1)).slice(-2);
		let day = ('0' + date.getDate()).slice(-2);
		let hours = ('0' + date.getHours()).slice(-2);
		let minutes = ('0' + date.getMinutes()).slice(-2);
		let seconds = ('0' + date.getSeconds()).slice(-2);
		let formattedDate = year + '/' + month + '/-' + day + ' ' + hours + ':' + minutes;
		return formattedDate
	}
}
// 将图片转为base64
export function getBase64Image(imageUrl) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: imageUrl,
			method: 'GET',
			responseType: 'arraybuffer',
			success: (res) => {
				let base64Image = uni.arrayBufferToBase64(res.data);
				base64Image = 'data:image/jpeg;base64,' + base64Image;
				resolve(base64Image)
			}
		})
	})
}
// 将base64变成图片
export function base64img(imgName, base64) {
	const filePath = `${uni.env.USER_DATA_PATH}/${imgName}.png`;
	return new Promise((resolve, reject) => {
		uni.getFileSystemManager().writeFile({
			filePath,
			data: base64,
			encoding: 'base64',
			success: (res) => {
				resolve(filePath)
			}
		})
	})
}
export function saveBase64Image(base64Data, fileName = 'image_' + Date.now()) {
  return new Promise((resolve, reject) => {
    // 检查是否是合法的base64格式
    if (!base64Data || !base64Data.startsWith('data:image/')) {
      return reject(new Error('无效的base64图片数据'));
    }
    
    // 提取图片类型
    const matches = base64Data.match(/^data:image\/([^;]+);base64,/);
    const imageType = matches && matches[1] ? matches[1] : 'png';
    const extension = imageType === 'jpeg' ? 'jpg' : imageType;
    
    // 去掉数据前缀
    const base64 = base64Data.replace(/^data:image\/[^;]+;base64,/, '');
    
    // 创建临时文件路径
    const filePath = `${uni.env.USER_DATA_PATH}/${fileName}.${extension}`;
    
    // 将base64转换为ArrayBuffer
    const buffer = uni.base64ToArrayBuffer(base64);
    
    // 写入文件
    uni.getFileSystemManager().writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success() {
        // 保存成功后，有些场景可能需要保存到相册
        // 注意：保存到相册需要用户授权（scope.writePhotosAlbum）
        resolve(filePath);
      },
      fail(err) {
        console.error('保存文件失败:', err);
        reject(new Error(`保存文件失败: ${err.errMsg}`));
      }
    });
  });
}

export function getImg(imageSrc) {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: imageSrc,
			success: (res) => {
				resolve(res.path)
			}
		})
	})
}

export async function payment(data) {
	let platformType = ''
	let pt = uni.getSystemInfoSync()
	if (pt.uniPlatform == "web") {
		platformType = ''
	} else {
		let payType = await getProvider('payment')
		platformType = payType[0]
	}
	if (pt.uniPlatform == "mp-weixin") {
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: platformType,
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: (res) => {
					resolve(true)
				},
				fail: (res) => {
					reject(false)
				}
			})
		})
	} else {
		data.appId = 'wx605015dae1f13bc4'
	}
}
export function getProvider(type) {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: type,
			success: (res) => {
				resolve(res.provider)
			}
		})
	})
}
// 获取二维码中的参数
export function getQrurl(scene) {
	if (scene) {
		let theRequest = new Object();
		let str = decodeURIComponent(scene);
		let strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
		}
		return theRequest
	}
}
// 推广
export function getTuiGuang(id) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://www.cnpowder.com.cn/user/miniprogramwx/txl.php?do=gettxlshareimg&txlid=' + id+'&codebase64=1',
			success: (res) => {
				let base64 = res.data
				resolve('data:image/jpeg;base64,' + base64)
			}
		});
	})
}
// 名片
export function getMingpian(userid, txlid) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://www.cnpowder.com.cn/user/miniprogramwx/txl.php?do=txlcardewm&userid=' +
				userid + '&txlid=' + txlid+'&codebase64=1',
			success: (res) => {
				let base64 = res.data;
				resolve('data:image/jpeg;base64,' + base64)
			}
		});
	})
}